package cn.yuysaln.domain.activity.service.quota.rule.impl;

import cn.yuysaln.domain.activity.model.entity.ActivityCountEntity;
import cn.yuysaln.domain.activity.model.entity.ActivityEntity;
import cn.yuysaln.domain.activity.model.entity.ActivitySkuEntity;
import cn.yuysaln.domain.activity.model.valobj.ActivitySkuStockKeyVO;
import cn.yuysaln.domain.activity.repository.IActivityRepository;
import cn.yuysaln.domain.activity.service.armory.IActivityDispatch;
import cn.yuysaln.domain.activity.service.quota.rule.AbstractActionChain;
import cn.yuysaln.types.enums.ResponseCode;
import cn.yuysaln.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component("activity_sku_stock_action")
public class ActivitySkuStockActionChain extends AbstractActionChain {

    @Resource
    private IActivityDispatch activityDispatch;
    @Resource
    private IActivityRepository activityRepository;

    @Override
    public boolean action(ActivitySkuEntity activitySkuEntity, ActivityEntity activityEntity, ActivityCountEntity activityCountEntity) {
        log.info("活动责任链-商品库存处理【有效期、状态、库存(sku)】开始。sku:{} activityId:{}", activitySkuEntity.getSku(), activityEntity.getActivityId());
        //先扣减缓存中的数据
        boolean isSubtracted = activityDispatch.subtractionActivitySkuStock(activitySkuEntity.getSku(), activityEntity.getEndDateTime());
        if (isSubtracted){
            log.info("活动责任链-商品库存处理【有效期、状态、库存(sku)】成功。sku:{} activityId:{}", activitySkuEntity.getSku(), activityEntity.getActivityId());

            //使用消息队列+定时任务同步数据库
            activityRepository.activitySkuStockConsumeSendQueue(
                    ActivitySkuStockKeyVO.builder() //sku + 活动 构成的VO
                            .sku(activitySkuEntity.getSku())
                            .activityId(activityEntity.getActivityId())
                            .build()
            );
            return true;
        }
       throw new AppException(ResponseCode.ACTIVITY_SKU_STOCK_ERROR.getCode(),ResponseCode.ACTIVITY_SKU_STOCK_ERROR.getInfo());
    }
}
